package com.cmwa.scbp.business.projectManager.service.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.stereotype.Service;

import com.cmwa.scbp.base.constants.Constant;
import com.cmwa.scbp.base.mvc.entity.Employee;
import com.cmwa.scbp.base.mvc.entity.Page;
import com.cmwa.scbp.base.mvc.entity.Result;
import com.cmwa.scbp.base.mvc.entity.SearchParam;
import com.cmwa.scbp.business.prdSellChannel.entity.PrdSellChannelVo;
import com.cmwa.scbp.business.product.entity.NavBizVo;
import com.cmwa.scbp.business.product.entity.PrdAccountVo;
import com.cmwa.scbp.business.product.entity.ProductInfoVo;
import com.cmwa.scbp.business.product.entity.ProjectInfoVo;
import com.cmwa.scbp.business.product.entity.SubProductInfoVo;
import com.cmwa.scbp.business.product.entity.TreFeeDetailVo;
import com.cmwa.scbp.business.projectManager.dao.NavBizDao;
import com.cmwa.scbp.business.projectManager.dao.ProjectManagerDao;
import com.cmwa.scbp.business.projectManager.service.ProjectManagerService;
import com.cmwa.scbp.sys.organization.entity.OrganizationVo;
import com.cmwa.scbp.sys.organization.service.OrganizationService;
import com.cmwa.scbp.sys.permission.authority.entity.AuthorityVo;
import com.cmwa.scbp.sys.permission.authority.service.AuthorityService;
import com.cmwa.scbp.sys.permission.dataAuthority.entity.AuthorityEnum;
import com.cmwa.scbp.utils.SessionUtils;

/**
 * 产品运营业务实现层
 * 
 * @author ex-jiangtao
 * @date 2019-01-22 15:33:47
 */
@Service
public class ProjectManagerServiceImpl implements ProjectManagerService {
	@Resource
	private ProjectManagerDao projectManagerDao;
	@Resource
	private NavBizDao navBizDao;
	@Resource
	private AuthorityService authorityService;
	@Resource
	private OrganizationService organizationService;
	
	@Override
	public Page<PrdSellChannelVo> findPrdDisChannelData(SearchParam sp) {
		List<PrdSellChannelVo> items =  projectManagerDao.findPrdDisChannelData(sp);
		return Page.create(items, sp.getStart(), sp.getLimit(), items.size());
	}

	@Override
	public Page<PrdAccountVo> findPrdAccountData(SearchParam sp) {
		List<PrdAccountVo> items =  projectManagerDao.findPrdAccountData(sp);
		return Page.create(items, sp.getStart(), sp.getLimit(), items.size());
	}

	@Override
	public Page<TreFeeDetailVo> findPrdFeeData(SearchParam sp) {
		List<TreFeeDetailVo> items =  projectManagerDao.findPrdFeeData(sp);
		return Page.create(items, sp.getStart(), sp.getLimit(), items.size());
	}

	@Override
	public NavBizVo findPrjNavBizData(String prdCode) {
		return navBizDao.findPrjNavBizData(prdCode);
	}

	@Override
	public List<ProjectInfoVo> findProductData(String[] prjprcstatStr) {
		String empId = null; 
		if (StringUtils.equals(SessionUtils.getEmployee().getEmpType(), "OUT")) {
		    // 传用户ID或管理人ID
			empId = SessionUtils.getEmployee().getID();
		}
		return projectManagerDao.findProductData(prjprcstatStr,empId);
	}
	
	@Override
	public Page<ProjectInfoVo> prdInfoListPage(SearchParam sp) {
		transferData(sp,"prdCategory");
		transferData(sp,"prjTerm");
		transferData(sp,"prjprcstat");
		Employee employee = SessionUtils.getEmployee();
		if (StringUtils.equals(employee.getEmpType(), "OUT")) {
			sp.getSp().put("empId", employee.getID());
		}
		
		List<ProjectInfoVo> items = projectManagerDao.prdInfoListPage(sp);
		return Page.create(items, sp.getStart(), sp.getLimit(), sp.getTotal());
	}

	/**
	 * 数据转换
	 * @param sp
	 * @param type
	 */
	private void transferData(SearchParam sp,String type) {
		String types = (String)sp.getSp().get(type);
		if (StringUtils.isNotBlank(types)) {
			sp.getSp().put(type, types.split(","));
		}else {
			sp.getSp().put(type, null);
		}
	}
	
	@Override
	public void export(HttpServletResponse response, SearchParam sp) throws IOException {
		transferData(sp,"prdCategory");
		transferData(sp,"prjTerm");
		transferData(sp,"prjprcstat");
		Employee employee = SessionUtils.getEmployee();
		if (StringUtils.equals(employee.getEmpType(), "OUT")) {
			sp.getSp().put("empId", employee.getID());
		}
		List<ProjectInfoVo> list = projectManagerDao.prdInfoList(sp);
		exportData(response,list);
	}
	
	@SuppressWarnings({"deprecation", "resource"})
	public void exportData(HttpServletResponse response,
			List<ProjectInfoVo> list) throws IOException{
		String curDateStr = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
		HSSFWorkbook wb = new HSSFWorkbook();
		
		// 样式
		HSSFCellStyle titleStyle = wb.createCellStyle();
		titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
		HSSFFont titleFont = wb.createFont(); // 创建字体
		titleFont.setFontName("宋体"); // 黑体
		titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 加粗
		titleStyle.setFont(titleFont);
		HSSFSheet sheet = wb.createSheet("产品信息");
		
		sheet.setColumnWidth(0, 20 * 256);
		sheet.setColumnWidth(1, 20 * 256);
		sheet.setColumnWidth(2, 20 * 256);
		sheet.setColumnWidth(3, 20 * 256);
		sheet.setColumnWidth(4, 20 * 256);
		sheet.setColumnWidth(5, 20 * 256);
		sheet.setColumnWidth(6, 20 * 256);
		sheet.setColumnWidth(7, 20 * 256);
		sheet.setColumnWidth(8, 20 * 256);
		sheet.setColumnWidth(9, 20 * 256);
		sheet.setColumnWidth(10, 20 * 256);
		HSSFRow row = sheet.createRow(0);// 生成头部信息
		
		String[] titleRow = new String[] {"产品编码","产品简称","产品分类","产品状态","运作模式","业务类型","募集方式","开放频率","成立时间","到期时间"};
		for (int i = 0; i < titleRow.length; i++) {
			HSSFCell cell = row.createCell(i, Cell.CELL_TYPE_STRING);
			cell.setCellValue(titleRow[i]);
			cell.setCellStyle(titleStyle);
		}

		//基本信息
		for (int i = 0; i < list.size(); i++) {
			ProjectInfoVo dto = list.get(i);
			HSSFRow rowData = sheet.createRow(i + 1);
			HSSFCell cell = null;
			
			cell = rowData.createCell(0, Cell.CELL_TYPE_STRING);
			cell.setCellValue(dto.getPrjcode());
			cell = rowData.createCell(1, Cell.CELL_TYPE_STRING);
			cell.setCellValue(dto.getPrjsname());
			cell = rowData.createCell(2, Cell.CELL_TYPE_STRING);
			cell.setCellValue(dto.getPrdCategoryNM());
			cell = rowData.createCell(3, Cell.CELL_TYPE_STRING);
			cell.setCellValue(dto.getPrjprcstatNM());
			cell = rowData.createCell(4, Cell.CELL_TYPE_STRING);
			cell.setCellValue(dto.getOperationModeNM());
			cell = rowData.createCell(5, Cell.CELL_TYPE_STRING);
			cell.setCellValue(dto.getPrdBizTypeNM());
			cell = rowData.createCell(6, Cell.CELL_TYPE_STRING);
			cell.setCellValue(dto.getCollectionMethodNM());
			cell = rowData.createCell(7, Cell.CELL_TYPE_STRING);
			cell.setCellValue(dto.getOpenFrequencyNM());
			cell = rowData.createCell(8, Cell.CELL_TYPE_STRING);
			cell.setCellValue(dto.getSetupDate());
			cell = rowData.createCell(9, Cell.CELL_TYPE_STRING);
			cell.setCellValue(dto.getExpectedEndDate());
			
		}
		// 相关的响应信息
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		String fileName = new String("产品信息导出".getBytes("GBK"), "ISO8859-1");
		response.setHeader("Content-Disposition", "Attachment;filename="
				+ fileName + "(" + curDateStr + ").xls");
		ServletOutputStream output = response.getOutputStream();
		wb.write(output);
		if (output != null) {
			output.close();
		}
	}

	@Override
	public ProjectInfoVo getPrdInfoByCode(String prdCode) {
		return projectManagerDao.getPrdInfoByCode(prdCode);
	}

	@Override
	public List<ProjectInfoVo> prdInfoList(SearchParam sp) {
		return projectManagerDao.prdInfoList(sp);
	}
	
	@Override
	public List<SubProductInfoVo> findSubProductInfo(String prjcode) {
		return projectManagerDao.findSubProductInfo(prjcode);
	}

	@Override
	public List<ProjectInfoVo> queryMatchProjectInfoList(SearchParam sp) {
		return projectManagerDao.queryMatchProjectInfoList(sp);
	}
	
	@Override
	public List<ProjectInfoVo> queryMatchProductInfoList(SearchParam sp) {
		return projectManagerDao.queryMatchProductInfoList(sp);
	}

	@Override
	public SubProductInfoVo querySubPrdInfoBySubPrdCode(String subPrdCode) {
		
		return projectManagerDao.querySubPrdInfoBySubPrdCode(subPrdCode);
	}

	@Override
	public List<ProjectInfoVo> queryMatchSubPrdInfoList(SearchParam param) {
		return projectManagerDao.queryMatchSubPrdInfoList(param);
	}
	
	@Override
	public List<ProjectInfoVo> queryMatchSubPrdLineList(SearchParam param) {
		return projectManagerDao.queryMatchSubPrdLineList(param);
	}

	@Override
	public void saveProjectData(ProjectInfoVo projectInfoVo) {
		projectManagerDao.saveProjectData(projectInfoVo);
	}

	@Override
	public void saveProductData(ProductInfoVo productInfoVo) {
		projectManagerDao.saveProductData(productInfoVo);
	}

	@Override
	public void saveSubProductData(SubProductInfoVo subProductInfoVo) {
		projectManagerDao.saveSubProductData(subProductInfoVo);
	}

	@Override
	public void productManagerDel(String prjcode, String prdcode, String subPrdcode) {
		String modifyId = SessionUtils.getEmployee().getID();//获取当前登录人
		SearchParam sp = new SearchParam();
		sp.getSp().put("prjcode", prjcode);
		sp.getSp().put("prdcode", prdcode);
		sp.getSp().put("subPrdcode", subPrdcode);
		sp.getSp().put("modifyId", modifyId);
		if(null != subPrdcode && !"".equals(subPrdcode)) {
			projectManagerDao.subProductDel(sp);
		}else if(null != prdcode && !"".equals(prdcode)) {
			projectManagerDao.productDel(sp);
			projectManagerDao.subProductDel(sp);
		}else {
			projectManagerDao.projectDel(sp);
			projectManagerDao.productDel(sp);
			projectManagerDao.subProductDel(sp);
			try {
				//删除数据权限
				if(StringUtils.isNoneEmpty(prjcode)){
					ProjectInfoVo projectInfoVo = projectManagerDao.getPrdInfoByCode(prjcode);
					projectInfoVo.setPrjcode(prjcode);
					cleanUpAuthority(projectInfoVo);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public List<PrdAccountVo> queryAccountTypeList(SearchParam param) {
		return projectManagerDao.queryAccountTypeList(param);
	}

	@Override
	public void addPrdAccountList(PrdAccountVo prdAccountVo) {
		//判断是否为“已有账户”
		if("1".equals(prdAccountVo.getAccClass())) {
			projectManagerDao.addBankAccount(prdAccountVo);
		}
		if(!"0".equals(prdAccountVo.getAccLevel())) {
			projectManagerDao.addPrjAccountRelations(prdAccountVo.getAccId(), prdAccountVo.getPrjcode(), prdAccountVo.getCreateId());
		}else if("0".equals(prdAccountVo.getAccLevel())) {
			projectManagerDao.addPrdAccountRelations(prdAccountVo.getAccId(), prdAccountVo.getPrdcode(), prdAccountVo.getCreateId());
		}
	}
	
	@Override
	public void delPrdAccountList(String accIds) {
		projectManagerDao.delPrjAccountRelations(accIds);
		projectManagerDao.delPrdAccountRelations(accIds);
	}
	
	@Override
	public List<PrdAccountVo> queryBankAccountInfoList(SearchParam sp) {
		return projectManagerDao.queryBankAccountInfoList(sp);
	}
	
	@Override
	public Result<T> checkAddAccountList(String accLevel,String accId, String code) {
		Result<T> result = new Result<T>();
		result.setSuccess(true);
		if(!"0".equals(accLevel)) {
			int count = projectManagerDao.findCountPrjAccountRelById(accId, code);
			if(count > 0) {
				result.setSuccess(false);
				result.setMessage("账户信息已存在当前系列产品中");
			}
		}else if("0".equals(accLevel)) {
			int count = projectManagerDao.findCountPrdAccountRelById(accId, code);
			if(count > 0) {
				result.setSuccess(false);
				result.setMessage("账户信息已存在当前产品中");
			}
		}
		return result;
	}
	
	@Override
	public void addAuthority(ProjectInfoVo projectInfoVo) throws Exception{
		String managerId = projectInfoVo.getManagerId();
		List<OrganizationVo> list = null;
		if(StringUtils.isNotBlank(managerId)){
			list = organizationService.queryOrganizationListByParentId(managerId);
		}
		
		if(CollectionUtils.isNotEmpty(list)){
			List<AuthorityVo> authorityList = new ArrayList<AuthorityVo>();
			for(OrganizationVo org : list){
				AuthorityVo authorityVo = AuthorityVo.builder()
						.setResourceId(projectInfoVo.getPrjcode())
						.setResourceType(Constant.ROLE_TYPE1)
						.setRoleType(Constant.ROLE_TYPE1) // 设置角色类型
						.setOrgId(org.getOrgId())
						.setEmpowermentWay(AuthorityEnum.DEPT)
						.build();
				authorityList.add(authorityVo);
			}
			authorityService.addAuthority(authorityList);
		}
	}
	
	@Override
	public void cleanUpAuthority(ProjectInfoVo projectInfoVo) throws Exception{
		String managerId = projectInfoVo.getManagerId();
		List<OrganizationVo> list = null;
		if(StringUtils.isNotBlank(managerId)){
			list = organizationService.queryOrganizationListByParentId(managerId);
		}
		
		if(CollectionUtils.isNotEmpty(list)){
			List<AuthorityVo> authorityList = new ArrayList<AuthorityVo>();
			for(OrganizationVo org : list){
				AuthorityVo authorityVo = AuthorityVo.builder()
						.setResourceId(projectInfoVo.getPrjcode())
						.setResourceType(Constant.ROLE_TYPE1)
						.setRoleType(Constant.ROLE_TYPE1) // 设置角色类型
						.setOrgId(org.getOrgId())
						.setEmpowermentWay(AuthorityEnum.DEPT)
						.build();
				authorityList.add(authorityVo);
			}
			authorityService.cleanUpAuthority(authorityList);
		}
	}

	@Override
	public void productManagerUpd(SearchParam sp) {
		projectManagerDao.projectUpd(sp);
		//判断是否需要修改子产品状态
		if(!"".equals(sp.getSp().get("subPrdcode"))) {
			projectManagerDao.subProductUpd(sp);
		}
	}
	
}
